package com.kim.rssreader.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;

/**
 * 正则表达式 过滤HTML源代码中的图片地址
 * 
 * @author Administrator
 * 
 */

public class ImgFilter {

	/**
	 * 无图模式下的默认图片
	 * 
	 */
	public static final String DEFAULT_IMG = "file:///android_asset/content_defaul_pic.png";

	public static final Pattern p = Pattern
			.compile(
					"<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>",
					Pattern.CASE_INSENSITIVE);

	public static String fliter(String htmlCode, Context context) {
		List<String> list = getImageSrc(htmlCode);
		for (int i = 0; i < list.size(); i++) {
			String imgUrl = (String) list.get(i);
			System.out.println("imgurl: " + imgUrl);
			htmlCode = htmlCode.replaceAll(imgUrl, DEFAULT_IMG);
		}

		return htmlCode;
	}

	public static List<String> getImageSrc(String htmlCode) {
		List<String> imageSrcList = new ArrayList<String>();
		if (null == htmlCode) {
			return imageSrcList;
		}
		Matcher m = p.matcher(htmlCode);
		String quote = null;
		String src = null;
		while (m.find()) {
			quote = m.group(1);
			src = (quote == null || quote.trim().length() == 0) ? m.group(2)
					.split("\\s+")[0] : m.group(2);
			imageSrcList.add(src);
		}
		return imageSrcList;
	}

}
